package com.syyo.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.enums.ResultEnum;
import com.syyo.common.exception.SysException;
import com.syyo.common.to.mq.OrderTo;
import com.syyo.common.to.mq.StockDetailTo;
import com.syyo.common.to.mq.StockLockTo;
import com.syyo.common.utils.MyJSONUtils;
import com.syyo.common.vo.SkuHasStockVo;
import com.syyo.gulimall.ware.config.rabbit.MyMQConfig;
import com.syyo.gulimall.ware.domain.entity.WareOrderTaskDetailEntity;
import com.syyo.gulimall.ware.domain.entity.WareOrderTaskEntity;
import com.syyo.gulimall.ware.domain.entity.WareSkuEntity;
import com.syyo.gulimall.ware.domain.req.WareSkuReq;
import com.syyo.gulimall.ware.feign.OrderFeign;
import com.syyo.gulimall.ware.mapper.WareOrderTaskDetailMapper;
import com.syyo.gulimall.ware.mapper.WareOrderTaskMapper;
import com.syyo.gulimall.ware.mapper.WareSkuMapper;
import com.syyo.gulimall.ware.service.WareSkuService;
import com.syyo.gulimall.ware.vo.OderItemVo;
import com.syyo.gulimall.ware.vo.OrderVo;
import com.syyo.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 商品库存
 *
 * @author syyo
 * @email syyo@gmail.com
 * @date 2021-01-20 10:06:54
 */
@Service
public class WareSkuServiceImpl extends ServiceImpl<WareSkuMapper, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuMapper wareSkuMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskDetailMapper wareOrderTaskDetailMapper;

    @Autowired
    private WareOrderTaskMapper wareOrderTaskMapper;

    @Autowired
    private OrderFeign orderFeign;

    /**
     * 新增
     */
    @Override
    @Transactional
    public int add(WareSkuReq req) {
        WareSkuEntity entity = new WareSkuEntity();
        // 添加创建时间和更新时间
        BeanUtils.copyProperties(req, entity);
        int insert = wareSkuMapper.insert(entity);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10001.getCode(), ResultEnum.E_10001.getMessage());
        }
        return insert;
    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public int del(Integer id) {
        int insert = wareSkuMapper.deleteById(id);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10002.getCode(), ResultEnum.E_10002.getMessage());
        }
        return insert;
    }

    /**
     * 编辑
     */
    @Override
    @Transactional
    public int edit(WareSkuReq req) {
        WareSkuEntity entity = new WareSkuEntity();
        // 添加更新时间
        BeanUtils.copyProperties(req, entity);
        int insert = wareSkuMapper.updateById(entity);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10003.getCode(), ResultEnum.E_10003.getMessage());
        }
        return insert;
    }

    /**
     * 详情
     */
    @Override
    public WareSkuEntity findOne(Integer id) {
        return wareSkuMapper.selectById(id);
    }

    /**
     * 列表
     */
    @Override
    public IPage<WareSkuEntity> findAll(Integer pageNum, Integer pageSize, WareSkuReq req) {

        Page<WareSkuEntity> teacherPage = new Page<WareSkuEntity>(pageNum, pageSize);
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        if (req.getSkuId() != null) {
            wrapper.eq("sku_id", req.getSkuId());
        }
        if (req.getWareId() != null) {
            wrapper.eq("ware_id", req.getWareId());
        }
        return wareSkuMapper.selectPage(teacherPage, wrapper);
    }

    @Override
    public List<SkuHasStockVo> findSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long count = wareSkuMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 锁定库存
     * <p>
     * 场景：
     * 1）、下订单成功，订单过期或者手动取消，都要解锁库存
     * 2）、下订单成功，库存锁定成功，后面的业务失败，导致回滚
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情
         *
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskMapper.insert(taskEntity);


        // 锁库存
        // 1.找个每个商品在哪个仓库有库存
        List<OderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();

            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            // 查询找个商品在哪个仓库有库存
            List<Long> wareIds = wareSkuMapper.listWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        boolean allLock = true;
        // 2.锁定库存
        for (SkuWareHasStock stock : collect) {
            boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                // 没有库存，
                throw new SysException(ResultEnum.E_16000.getCode(), ResultEnum.E_16000.getMessage() + skuId);
            }
            // 1.如果每一个商品都锁定成功，将当前商品锁定了纪检的工作单记录发给mq
            // 2.如果锁定失败前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁记录，由于数据库没有
            for (Long wareId : wareIds) {
                Integer count = wareSkuMapper.lockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    skuStocked = true;

                    // todo
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", stock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailMapper.insert(entity);

                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity, stockDetailTo);
                    // 发送消息
                    StockLockTo lockTo = new StockLockTo();
                    lockTo.setId(taskEntity.getId());
                    lockTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend(MyMQConfig.STOCK_EXCHANGE, MyMQConfig.STOCK_LOCKED_KEY, lockTo);
                    break;
                }
                // 当前仓库锁失败了，继续下一个仓库
            }

            if (!skuStocked) {
                // 当前商品的所有仓库都没锁住
                throw new SysException(ResultEnum.E_16000.getCode(), ResultEnum.E_16000.getMessage() + skuId);
            }
        }
        // 肯定全部锁定成功
        return true;


    }

    /**
     * 解锁库存
     * 1、查询数据库关于这个订单的锁定库存信息
     * 有：正面锁定成功了，
     * 解锁：订单情况
     * 1、没有这个订单，必须解锁
     * 2、有这个订单，
     * 判断订单状态，已取消，解锁库存，没取消不能解锁
     * 没有：库存锁定失败了，本地事务会自动库存回滚了，这种情况无需解锁
     */
    @Override
    public void unLockStock(StockLockTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailMapper.selectById(detailId);
        if (detailEntity != null) {
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskMapper.selectById(id);
            String orderSn = taskEntity.getOrderSn();
            // 根据订单号查询订单状态
            ResultVo resultVo = orderFeign.getOrderStatus(orderSn);
            if (resultVo.getCode() == 20000) {
                // 发送请求成功
                OrderVo orderVo = MyJSONUtils.typeCast(new TypeReference<OrderVo>() {
                }, resultVo.getData());
                if (orderVo == null || orderVo.getStatus() == 4) {
                    // 订单不存在、订单被取消了，都要解锁库存
                    // 当前库存工作单详情状态是已锁定才能解锁
                    if (detailEntity.getLockStatus() == 1) {
                        unLockStock(detail.getSkuId(), detail.getSkuNum(), detail.getWareId(), detailId);
                    }
                }
            } else {
                throw new SysException(ResultEnum.E_90007.getCode(), ResultEnum.E_90007.getMessage());
            }
        }

    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存消息优先到期，查询订单为新建状态，什么都不做
     * 卡顿的订单，永久不能解锁库存
     *
     * @param to
     */
    @Transactional
    @Override
    public void unLockStock(OrderTo to) {

        String orderSn = to.getOrderSn();
        // 查一下最新的库存状态
        WareOrderTaskEntity task = wareOrderTaskMapper.selectOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));

        // 按照工作单，找到所有没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailMapper.selectList(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", task.getId())
                .eq("lock_status", 1));

        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(), entity.getSkuNum(), entity.getWareId(), entity.getId());
        }
    }


    /**
     * @param skuId    商品id
     * @param num      库存数量
     * @param wareId   仓库id
     * @param detailId 工作单id
     */
    private void unLockStock(Long skuId, Integer num, Long wareId, Long detailId) {
        // 库存解锁
        wareSkuMapper.unLockStock(skuId, wareId, num);
        // 库存工作单也修改状态

        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(detailId);
        detailEntity.setLockStatus(2);
        wareOrderTaskDetailMapper.updateById(detailEntity);
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}